﻿using System;
using System.Collections.Generic;
using Wombat.Core.Diagnostics;
using Wombat.Core.Services;
using Wombat.Data.Model;
using Wombat.Common;
using IDataService = Wombat.Core.Services.IDataService;

namespace Wombat.Core.Gates
{
    public abstract class StorageBaseGate: IGate, IConfigurable, IDiagnosticsObservable, ILongLifeGate, IInitializable
    {
        private readonly IConfigurationService _configService;
        protected readonly IDataService DatabaseService;
        protected readonly ITagRpository TagRpository;

        public static readonly string DataPort = "DataPort";
        public static readonly string DiagnosticsPort = "DiagnosticsPort";

        protected StorageBaseGate(IConfigurationService configService, IDataService databaseService, ITagRpository tagRpository)
        {
            _configService = configService;
            DatabaseService = databaseService;
            TagRpository = tagRpository;
        }

        protected abstract void SetupPorts();

        #region Implementation of IGate

        public Guid Guid { get; protected set; }

        public IEnumerable<IPort> Ports { get; protected set; }

        #endregion

        #region Implementation of IConfigurable

        public IDictionary<string, IConfigurationItem> Configurations { get; private set; }

        #endregion

        #region Implementation of IDiagnosticsObservable

        public void SubscribeDiagnostics(DiagnosticsLevel level, IObserver<IDiagnosticsMessage> errorObserver)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Implementation of IDisposable

        public void Dispose()
        {
        }

        #endregion

        #region Implementation of IInitializable

        public void Initialize()
        {
            Configurations = _configService.ReadConfigurations(GetType());

            if (Configurations.ContainsKey(DatabaseServiceConfigKeys.ConnectionString))
            {
                DatabaseService.ConnectionString = Configurations[DatabaseServiceConfigKeys.ConnectionString].NullSafe(c => c.Value) as string;
            }
            Guid = Configurations.ContainsKey(DatabaseServiceConfigKeys.Guid) ? 
                Guid.Parse((string) Configurations[DatabaseServiceConfigKeys.Guid].Value) :
                Guid.NewGuid();
            SetupPorts();
        }

        #endregion
    }
}
